// @author caoshi
// @date 2023/2/14 9:51
// @since 1.0
package controllers

import (
	"beegodemo04/models"
	"beegodemo04/utils"
	"encoding/json"
	"fmt"
)

// 自定义的Controller就不需要再继承beego.Controller 了， 否则报错 “beegodemo04:assignment to entry in nil map”
type BookController struct {
	utils.ResponseController
}

// 返回数据是Map类型
func (c *BookController) GetBookById() {

	// get 请求获取 url 参数
	name := c.GetString("name")
	age, _ := c.GetInt("age")
	fmt.Println(name, age)

	resp := make(map[string]interface{})
	resp["BookName"] = "朝花夕拾"
	resp["Price"] = 18
	resp["Author"] = "鲁迅"

	c.Success("", resp)
}

// 返回数据是实体对象
func (c *BookController) GetBookById2() {

	// 获取占位符参数
	// router写法 beego.Router("/book/getBookById2/?:name/?:age", &controllers.BookController{}, "get:GetBookById2")
	name := c.GetString(":name")
	age, _ := c.GetInt(":age")
	fmt.Printf(name, age)

	book := models.Book{
		BookName: "朝花夕拾",
		Price:    28.8,
		Author:  models.Author{
			Name: "鲁迅",
			Age: 50,
			Hobbies: []string{"抽烟", "喝酒", "烫头"},
		},
	}
	c.SuccessNonMsg(book)
}

// 定义一个结构体接收POST请求参数
type User struct {
	Name string `json:"name"`
	Age int	`json:"age"`
}

// 测试post请求传参
func (c *BookController) SaveBook() {

	body := c.Ctx.Input.RequestBody
	// 存入map中
	params := make(map[string]interface{})
	_ = json.Unmarshal(body, &params)

	//
	var u User
	_ = json.Unmarshal(body, &u)
	fmt.Println(u)

	fmt.Println(params)
	c.SuccessNonMsg(u)
}






